package pl.edu.pw.MidEmu.UI.Components;

import java.awt.Component;
import java.lang.reflect.Method;

/**
 * Helper class managing window repainting when certain events occurs
 * Used by process handlers and process output handlers
 * @author Mateusz Starodab
 *
 */
public class Repainter extends Thread
{
	private boolean componentMode;
	private Object invocationTarget;

	private String methodName;
	private boolean run = true;
	private Component subscriber;

	private String typeName;

	public Repainter(Component subscriber)
	{
		componentMode = true;
		this.subscriber = subscriber;
	}

	public Repainter(String type, String method, Object target)
	{
		componentMode = false;
		typeName = type;
		methodName = method;
		invocationTarget = target;
	}

	@Override
	public void run()
	{
		while (run)
		{
			if (componentMode)
			{
				subscriber.repaint();
			}
			else
			{
				try
				{
					Class o = Class.forName(typeName);
					Method m = o.getMethod(methodName, null);
					m.invoke(invocationTarget, null);
				}
				catch (Exception e)
				{
					e.printStackTrace();
				}
			}

			try
			{
				sleep(1000);
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}
		}
	}

	public void terminate()
	{
		run = false;
	}
}
